import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
// 下面路由路径(不是文件地址随便写)
const routes = [
  {
    path: '/', // 第一次打开网页默认访问/路由 (或者点击a标签, 跳到/路由)
    redirect: '/layout' // 虽然直接取layout页面(但是你有路由守卫, 未登录还是会被to打回到/login)
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/Login')
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('@/views/Layout/Layout'),
    redirect: '/layout/home', // 默认进到layout页面, 马上显示二级home页面
    // 二级路由配置-组件根据路径-显示在Layout.vue中router-view上
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import('@/views/Home/Home')
      },
      {
        path: 'addArticle',
        name: 'addArticle',
        // 网站打开后, 上面import都会执行(无论页面用不用都加载到变量里浪费内存)
        // 只有路径命中后, 才开始import导入组件(import不是ES6语法而是webpack提供的方法)
        component: () => import('@/views/Article/ArticleAdd')
      },
      {
        path: 'articleList',
        name: 'articleList',
        component: () => import('@/views/Article/ArticleList')
      },
      {
        path: 'image',
        name: 'images',
        component: () => import('@/views/Images/Images')
      },
      {
        path: 'comment',
        name: 'comment',
        component: () => import('@/views/Comment/Comment')
      },
      {
        path: 'fans',
        name: 'fans',
        component: () => import('@/views/Fans/Fans')
      },
      {
        path: 'settings',
        name: 'settings',
        component: () => import('@/views/Settings/Settings')
      }
    ]
  },
  {
    path: '*', // 匹配除了以上的其他所有路径(必须写在最后)
    name: '404',
    component: () => import('@/views/404/404')
  }
]

const router = new VueRouter({
  routes
})

// 页面是靠路由切换的, 路由(导航)守卫, 判断下有无权限, 再决定是否跳转
router.beforeEach((to, from, next) => {
  // 去的正常界面, 并且还没有token, 进入if强制跳回到login页面
  if (to.path !== '/login' && !sessionStorage.getItem('token')) {
    next('/login')
  } else {
    next() // 如果去/login就正常放行, 上面条件token有值, 也正常放行
  }
})

export default router
